from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
# Create your views here.
from ..models import Types

from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import permission_required
from lzy.settings import BASE_DIR
import os

def index(request):
    
    return render(request,'admin/index.html')


# @permission_required('myadmin.insert_types',raise_exception = True)
def GetTypesAll():
    # 获取所有的商品类别
    # typelist = Types.objects.all()
    # select *, concat(path,id) as pats from myadmin_types order by paths;
    typelist = Types.objects.extra(select = {'paths':'concat(path,id)'}).order_by('paths')
    # typelist = Types.objects.extra(select = {'paths':'concat(path,id)'}).order_by('paths')
    for x in typelist:
        # 判断是否为顶级
        if x.pid == 0:
            x.pname = "顶级分类"
        else:
            ob = Types.objects.get(id=x.pid)
            x.pname = ob.name
        # 返回数据
        return typelist

# 分类的列表
@permission_required('myadmin.show_types',raise_exception = True)
def typesindex(request):
    # 分配数据
    # context = {'typelist':GetTypesAll()}

# 读取数据

    types = GetTypesAll()

    # 接受参数
    keys = request.GET.get('types',None)
    keywords = request.GET.get('keywords',None)
    print(keys,keywords)
    # 判断是否有搜索条件

    if keys:
        
        if keys == 'all':
        # 多字段的查询
            from django.db.models import Q
            typelist = types.filter(Q(name__contains=keywords)|Q(path__contains=keywords))
        else:
            data ={keys+'__contains':keywords}
            print(data)
            typelist = types.filter(**data)


 # 数据分页
    from django.core.paginator import Paginator
    # 实例化分页对象
    p = Paginator(types,10)
    # 获取当前的页码数
    page = request.GET.get('page',1)
    # 获取当前页的数据
    typelist = p.page(page)
    # 获取所有的页码列表
    # pages = p.page_range

    # 分配数据
    context = {'typelist':typelist}

    # 加载模板
    return render(request,'admin/types/index.html',context)

# 分类的添加
@permission_required('myadmin.insert_types',raise_exception = True)
def typesadd(request):
    # 分配数据
    context = {'typelist':GetTypesAll()}

    # 加载模板
    return render(request,'admin/types/add.html',context)


# 执行分类的添加
# def typesinsert(request):
    # try:
        # 接收数据
    # data = request.POST.dict()
    # data.pop('csrfmiddlewaretoken')

    # # 判断当前添加的是否为顶级分类
    # if data['pid'] == '0' :
    #     data['path'] == '0,'
    # else:
    #     # 获取父级对象
    #     ob = Types.objects.get(id=data['pid'])

    #     # 根据父级的path和当前我选择的pid+',' 进行拼接
    #     data['path'] = ob.path+data['pid']+','

    # # 创建对象 
    # Types.objects.create(**data)
@permission_required('myadmin.insert_types',raise_exception = True)
def typesinsert(request):
    try:
        # 接受数据
        data = request.POST.dict()
        data.pop('csrfmiddlewaretoken')

        # 判断当前添加的是否为顶级分类
        if data['pid'] == '0':
            data['path'] = '0,'
        else:
            # 获取父级对象
            ob = Types.objects.get(id=data['pid'])
            # 根据父级的path和我当前选择的pid+',' 进行拼接
            data['path'] = ob.path+data['pid']+','

        # 创建对象
        Types.objects.create(**data)
        # 跳转到列表页
        return HttpResponse('<script>alert("添加成功");location.href="'+reverse('myadmin_types_index')+'"</script>')
    except:
        return HttpResponse('<script>alert("添加失败");location.href="'+reverse('myadmin_types_add')+'"</script>')


    # 跳转到列表页
    # return HttpResponse('<script>alert("添加成功");location.href="/myadmin/types/index/"<script>')
    # except:
        # return HttpResponse('<script>alert("添加成功");location.href="/myadmin/types/add/"</script>')

# 执行分类的删除
@permission_required('myadmin.del_types',raise_exception = True)
def typesdelete(request):
    # 接受id,获取对象
    ob = Types.objects.get(id=request.GET['id'])
    # 判断当前类下是否还有子类
    if Types.objects.filter(pid=ob.id).count():
        # 有子类,不会删除
        return JsonResponse({'error':1,'msg':'当前类下有子类,不允许删除'})
    

    # 没有子类,也没有商品
    ob.delete()
    return JsonResponse({'error':0,'msg':'删除成功'})




# 执行分类的修改
@permission_required('myadmin.edit_types',raise_exception = True)
def typesupdate(request):
    try:
        # 根据id获取对象
        ob = Types.objects.get(id=request.GET['id'])
        # 修改
        ob.name =request.GET['name']
        ob.save()
        return JsonResponse({'error':0,'msg':'更新成功'})
    except: 
        return JsonResponse({'error':1,'msg':'更新失败'})

    









